﻿ 
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace Utils.Common
{
   public class FileHelper
    {

       /// <summary>
       /// 配置序列化保存
       /// </summary>
      public static bool  Serialize<T>(T s,string filename)
       {
            FileStream fileStream = null;
            try
            {
                fileStream = new FileStream(filename, FileMode.Create);
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(fileStream, s);
                fileStream.Close();
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.LogError(ex.Message, ex);
                
                return false;
            }
            finally {
                if(fileStream!=null)
                fileStream.Close();
            }
          
       }


      /// <summary>
      /// 配置反序列化读取
      /// </summary>  
      public static T BackSerialize<T>(string path) where T : ConfigBase 
      {

            if (!File.Exists(path)) return null;
            FileStream fileStream = null;
            try
            {
                fileStream= new FileStream(path, FileMode.Open);
                BinaryFormatter formatter = new BinaryFormatter();
                T t = formatter.Deserialize(fileStream) as T;
                fileStream.Close();
                return t;
            }
            catch (Exception ex)
            {
                LogHelper.LogError(ex.Message, ex);
               
                return null;
            }
            finally {
                if (fileStream != null)
                    fileStream.Close();
            }
      }
       /// <summary>
       /// 
       /// </summary>
       /// <param name="fliePath"></param>
       /// <param name="mes"></param>
       /// <returns></returns>
        public static bool  WriteToFile(string fliePath ,string mes)
        {
            try
            {
                var utf8WithoutBom = new System.Text.UTF8Encoding(false);
                StreamWriter sw = new StreamWriter(fliePath, false, utf8WithoutBom); // false 存在则覆盖
                sw.Write(mes);
                sw.Flush();
                sw.Close();
                return true;
            }
            catch (Exception ex){
                LogHelper.LogError(ex.Message, ex);
                return false;
            }

        }

        /// <summary>
        /// 读文件
        /// <summary>
        public static string  ReadFromFile(string fliePath )
        {
            try
            {
                FileStream fs = new FileStream(fliePath, FileMode.Open);
                StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);
                string mes = sr.ReadToEnd();
                sr.Close();
                fs.Close();
                return mes;
            }
            catch (IOException ex)
            {
                //LogHelper.LogError(ex.Message, ex);
                return ex.Message;
            }

        }



        /**
      * 过滤文件名中的非法字符,并返回新的名字.
      *
      * @param fileName 原文件名.
      * @return 过滤后的结果.
      */
        public static String FilterFileName(String fileName)
        {
            foreach (char c in Path.GetInvalidFileNameChars())
            {
                fileName = fileName.Replace(c.ToString(), "");
            }

            return fileName;
        }



        public static FileInfo[] GetFileInfos(string folderFullName)
        {
            DirectoryInfo theFolder = new DirectoryInfo(folderFullName);

            return  theFolder.GetFiles().OrderByDescending(s=>s.CreationTime ).ToArray();

        }


        /// <summary>
        /// 清空指定的文件夹，但不删除文件夹
        /// </summary>
        /// <param name="dir"></param>
        public static void DeleteFolder(string dir)
        {
            foreach (string d in Directory.GetFileSystemEntries(dir))
            {
                if (File.Exists(d))
                {
                    try
                    {
                        FileInfo fi = new FileInfo(d);
                        if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                            fi.Attributes = FileAttributes.Normal;
                        File.Delete(d);//直接删除其中的文件 
                    }
                    catch
                    {

                    }
                }
                else
                {
                    try
                    {
                        DirectoryInfo d1 = new DirectoryInfo(d);
                        if (d1.GetFiles().Length != 0)
                        {
                            DeleteFolder(d1.FullName);////递归删除子文件夹
                        }
                        Directory.Delete(d);
                    }
                    catch
                    {

                    }
                }
            }
     
        }
        /// <summary>
        /// 删除文件夹及其内容
        /// </summary>
        /// <param name="dir"></param>
        public static void DeleteContainFolder(string dir)
        {
            foreach (string d in Directory.GetFileSystemEntries(dir))
            {
                if (File.Exists(d))
                {
                    FileInfo fi = new FileInfo(d);
                    if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                        fi.Attributes = FileAttributes.Normal;
                    File.Delete(d);//直接删除其中的文件 
                }
                else
                    DeleteFolder(d);////递归删除子文件夹
                Directory.Delete(d);
            }
        }



        /// <summary>
        /// 复制文件
        /// </summary>
        /// <param name="sourcefile"></param>
        /// <param name="targetfile"></param>
        public static void CopyFile(string sourcefile, string targetfile)
        {

            File.Copy(sourcefile, targetfile,true);
        }

    }
}
